REST API 應該使用屬性路由,將應用程式的功能模型化為一組資源,其中作業會以 HTTP 動詞來表示。屬性路由使用一組屬性,將動作直接對應至路由範本。
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
在上述程式碼中, 呼叫 MapControllers 以對應屬性路由控制器。
[HttpGet]
[HttpPost]
[HttpPut]
[HttpDelete]
[HttpHead]
[HttpPatch]
[Route("api/[controller]")]
[ApiController]
public class Test2Controller : ControllerBase
{
    [HttpGet]   // GET /api/test2
    public IActionResult ListProducts()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }
    [HttpGet("{id}")]   // GET /api/test2/xyz
    public IActionResult GetProduct(string id)
    {
       return ControllerContext.MyDisplayRouteInfo(id);
    }
    [HttpGet("int/{id:int}")] // GET /api/test2/int/3
    public IActionResult GetIntProduct(int id)
    {
        return ControllerContext.MyDisplayRouteInfo(id);
    }
    [HttpGet("int2/{id}")]  // GET /api/test2/int2/3
    public IActionResult GetInt2Product(int id)
    {
        return ControllerContext.MyDisplayRouteInfo(id);
    }
}
在上述程式碼中:
[HttpGet] 屬性,只有 GET 方法可以存取。{id},例如 /api/test2/xyz、/api/test2/123、/api/test2/{any string} 都會進入此 Action。[HttpGet("int/{id:int}")] 
public IActionResult GetIntProduct(int id)
{
    return ControllerContext.MyDisplayRouteInfo(id);
}
GetIntProduct Action 包含 int/{id:int} 。 :int 的部分會將 id 路由值限制為可轉換成整數的字串。如果 Request 為 /api/test2/int/abc 則不符合此 Routing ,回傳 404 Not Found 。
[HttpGet("int2/{id}")]
public IActionResult GetInt2Product(int id)
{
    return ControllerContext.MyDisplayRouteInfo(id);
}
GetInt2Product Action 包含 {id},但不會限制 id 可轉換成整數的值。如果 Request 為 /api/test2/int2/abc,符合此 Routing,但 id 方法的參數是整數,Model無法將 abc 轉換成整數,故回傳 400 Bad Request。
[ApiController]
public class MyProductsController : ControllerBase
{
    [HttpGet("/products3")]
    public IActionResult ListProducts()
    {
        return ControllerContext.MyDisplayRouteInfo();
    }
    [HttpPost("/products3")]
    public IActionResult CreateProduct(MyProduct myProduct)
    {
        return ControllerContext.MyDisplayRouteInfo(myProduct.Name);
    }
}
使用 URL 路徑 /products3 :MyProductsController.ListProducts Action 會在 HTTP Method 為 GET 時執行。MyProductsController.CreateProduct Action 會在 HTTP Method 為 POST 時執行。
Routing to controller actions in ASP.NET Core